var defaults = {
    //datepicker default
    days:        ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
    daysShort:   ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    daysMin:     ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'],
    months:      ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    meridiem:    ['am', 'pm'],
    suffix:      ['st', 'nd', 'rd', 'th'],
    datepicker:{
        dateFormat:"yy-mm-dd",
        defaultDate: "today",
        changeMonth: true,
        prevText: '<i class="fa fa-chevron-left"></i>',
        nextText: '<i class="fa fa-chevron-right"></i>',
        numberOfMonths: 1,
        showButtonPanel: true
    }
};
var validator;

$.fn.extend({
    setSwitch : function(state){
        return this.each(function(){
            var $this = $(this);
            var $hidden = $this.parents(".controls").find("input[type=hidden]");
            $this.bootstrapSwitch('state',state);
            state==true? $hidden.val('true'):$hidden.val('false');
        })
    }
});
String.prototype.bool = function() {
    if((/^true$/i).test(this)){
        return {"value":true};
    }else if((/^false$/i).test(this)){
        return {"value":false};
    }else{
        return false;
    }
};
String.prototype.numerical = function(){
    return (/^([1-9]\d*|0|[1-9]\d{0,2})(\d*|\.\d+|(,\d{3})*)$/).test(this);
};
jQuery.prototype.serializeObject=function(){
    var obj=new Object();
    var value ;
    $.each(this.serializeArray(),function(index,param){
        if(!(param.name in obj)){
             //解决中文乱码
            value = decodeURIComponent(param.value,true);
            var isBoolean = value.bool();
            var isNumber = value.numerical();
            if(isBoolean){
                obj[param.name] = isBoolean.value;
            }else if(isNumber){
                obj[param.name] = Number(value);
            }else{
                obj[param.name] = value;
            }
        }
    });
    return obj;
};

function initSwitch(){
    //bootstrapSwitch default
    $.fn.bootstrapSwitch.defaults.onColor = 'success';
    $.fn.bootstrapSwitch.defaults.handleWidth = 4;
    $.fn.bootstrapSwitch.defaults.labelWidth = 1;
    $.fn.bootstrapSwitch.defaults.onText = '';
    $.fn.bootstrapSwitch.defaults.offText = '';

    $("[data-control-mode=switch]").bootstrapSwitch()
        .on("switchChange.bootstrapSwitch",function(event,state){
            $(this).setSwitch(state);
        });
}
/*--------  setSwitch  ---------*/
function setSwitchForConstant(state){
    $("[data-control-mode=switch]").setSwitch(state);
}
function setSwitchTrue(){
    setSwitchForConstant(true);
}
function setSwitchFalse(){
    setSwitchForConstant(false);
}
function setSwitchForRequest(json){
    var url = json.url;
    var data = json.data;
    $.post(url,data,function(result){       // return false|true
        var $input;
        var name;
        var $checkbox ;
        var data = { //result
            //1
            subaccount_email: "12@122.com",
            modify_campaign_settings: true,
            download_emails: false,
            start_campaigns: true,
            view_sales_stats: false,

            //2
            active:true
        };
        $("[data-control-mode=switch]").each(function(){
            $input = $(this);
            name = $input.parents(".controls").find("input[type=hidden]").attr("name");
            $input.setSwitch(data[name]);
        })
    })
}
/*--------  end setSwitch  ---------*/



/*--------  validatorForm  ---------*/
function validatorForm(data){
    //variable
    var $container = $(data.container);
    var callback = data.callback || null;
    var rules = data.rules || {};
    var min_checkbox = data.minCheckbox || 0 ;
    //main
    var id = $container.find("form").attr("id");
    var $form = $("#"+id);
    validator = $form.validate({
        rules:rules,
        submitHandler: function(form){   //表单提交句柄,为一回调函数，带一个参数：form
            if(min_checkbox>0){
                var length = $form.find("input:checked").length;
                if(length<min_checkbox){
                    $(".permission-error").removeClass("hide");
                }else{
                    $(".permission-error").addClass("hide");
                    submitForm();
                }
            }else{
                submitForm();
            }

            function submitForm(){
                if($form.valid()){
                    var params = $form.serializeObject();         //序列化

                    $container.modal('hide');
                    callback && callback.call(this,params);
                }
            }
        }
    });
}
function validatorFormEasy(data){
    //variable
    var $container = $(data.container);
    var callback = data.callback || null;
    var rules = data.rules || {};
    var $form;
    //main
    var id = $container.find("form").attr("id");
    if(id && typeof id !== undefined){
        $form = $("#"+id);
    }

    validator = $form.validate({
        rules:rules,
        submitHandler: function(form){   //表单提交句柄,为一回调函数，带一个参数：form
            if($form.valid()){
                var params = $form.serializeObject();         //序列化

                callback && callback.call(this,params);
            }
        }
    });
}
/*--------  end validatorForm  ---------*/

function loadTemplate(){
    var $body = $("body");
    var tempPath = './template/';
    var bodyClass = $body.attr("class");

    //load template
    if(bodyClass && bodyClass != ''){
        var bodyClassArr = bodyClass.split(" ");
        var newId ,loadName;
        for(var i=0,l=bodyClassArr.length;i<l;i++){
            newId = 'load'+i;
            loadName = bodyClassArr[i].substr(4)+'.html';
            if(bodyClassArr[i].indexOf('nav')!=-1 || bodyClassArr[i].indexOf('header')!=-1 ){
                $body.prepend("<div id='"+newId+"'></div>");
                $("#"+newId).load(tempPath+loadName);
            }else{
                $body.append("<div id='"+newId+"'></div>");
                $("#"+newId).load(tempPath+loadName);
            }

        }
    }
}
function pluginSettings(){
    //validation default
    if(jQuery.validator){
        jQuery.validator.setDefaults({ ignore: ".ignore_validate,:hidden" });
    }

    // popover default
    $('[data-toggle="popover"]').popover({ trigger:'hover' });
}
function setMinHeight(){
    var $body = $("body");
    var windowHeight = $(window).height();
    var footerHeight = $("footer").outerHeight();
    var headerHeight = $("header").outerHeight();
    var contentHeight = 0;

    //min-height settings
    $("main>section").each(function(){contentHeight += $(this).outerHeight();});
    var minHeight = windowHeight-footerHeight-headerHeight;

    if(minHeight > contentHeight){
        $("main").css({"min-height":minHeight});
    }else{
        return;
    }
}
function initDropdownSelect(json){
    var url = json.url || '#';
    var params = json.params || {};
    var controlElement = json.controlElement || 'table';

    $(document).on("click",".dropdown-select .dropdown-menu a",function(){
        var $this = $(this);
        var text = $this.text();
        params["value"] = $this.attr("data-value");

        $.get(url,params,function(result){
            $this.parents(".dropdown-select").find("button").html(text);
            $(controlElement).bootstrapTable('load', result);
        })
    });
}
function resetFormValidate(){
    var $form =  $(this).find("form");
    $form.get(0).reset();
}
/*
 参数：( 'c_from','c_to'   )
 (string,string)
 开始日期和结束日期的datepicker初始化
 */
function initDatetimeFromTo(fromId,toId,formId){
    // Date Range Picker
    var formId = fromId || 'form';
    var toId = toId || 'to';
    var dateFormat = "yy-mm-dd",
        from = $( "#"+fromId)
            .datepicker({

                onClose:function(){

                }
            })
            .on( "change", function() {
                to.datepicker( "option", "minDate", getDate( this ) );
                // $('form').bootstrapValidator('updateStatus', 'select_date_Y_from','VALID');
            }),
        to = $("#"+toId )
            .datepicker({
                defaultDate: "+1w",
                dateFormat:dateFormat,
                changeMonth: true,
                prevText: '<i class="fa fa-chevron-left"></i>',
                nextText: '<i class="fa fa-chevron-right"></i>',
                numberOfMonths: 1
            })
            .on( "change", function() {
                from.datepicker( "option", "maxDate", getDate( this ) );
                // $('form').bootstrapValidator('updateStatus', 'select_date_Y_to','VALID');
            });

    function getDate( element ) {
        var date;
        try {
            date = $.datepicker.parseDate( dateFormat, element.value );
        } catch( error ) {
            date = null;
        }

        return date;
    }
}
/*
*
*
*
*           FORMATTER
*
*
*
* */
function priceFormatter(value){
    return "$"+value.toFixed(2);
}
function dateStatusFormatter(value){
    if(value){
        return '<span class="label label-success">Active</span>';
    }else{
        return '<span class="label label-warning">Invalid</span>';
    }

}
function editFormatter(value){
    return '<a href="#" data-toggle="modal" data-target=".admin-modal-edit" data-backdrop="static" class="a-clean"><i class="fa fa-edit"></i></a>';
}
function IconBoolFormatter(value){
    if(value){
        return '<i class="fa fa-check-circle color-success"></i>';
    }else{
        return '<i class="fa fa-times-circle color-error"></i>';
    }
}

function activeBoolFormatter(value){
    if(value){
        return '<i class="fa fa-check-circle color-active"></i>';
    }else{
        return '<i class="fa fa-check-circle color-disabled"></i>';
    }
}
function getDateJson(str){
    var dateStr = str;
    var dateArr = dateStr.split("-");
    var dateJson = {};
    var d;
    dateJson.y = dateArr[0];
    dateJson.m = defaults.months[Number(dateArr[1])-1];
    dateJson.d = Number(dateArr[2]);
    return dateJson;
}
function getDateJsonClean(str){
    var dateStr = str;
    var dateArr = dateStr.split("-");
    var dateJson = {};
    dateJson.y = dateArr[0];
    dateJson.m = Number(dateArr[1])-1;
    dateJson.d = Number(dateArr[2]);
    return dateJson;
}
function dateMonthFormatter(value){
    var dateJson = getDateJson(value);
    return dateJson.m+" "+dateJson.d+", "+dateJson.y;
}
function lt9Formatter(number){
    return number > 9 ? number.toString() : "0"+number;
}
function dateDayFormatter(value){
    var dateJson = getDateJsonClean(value);
    var day_index = (new Date(dateJson.y,dateJson.m,dateJson.d)).getDay();
    return defaults.days[day_index]+", "+defaults.months[dateJson.m]+" "+dateJson.d;
};

function EandDFormatter(value, row, index){
    return [
        '<a href="javascript:void(0)" data-toggle="modal" data-target=".admin-modal-edit" data-backdrop="static" class="a-clean" title="Edit"><i class="fa fa-edit"></i></a>',
        '<a class="icon-times a-clean remove fa-wrapper" href="javascript:void(0)" data-toggle="modal" data-target=".admin-modal-del" data-backdrop="static" title="Remove"></a>'
    ].join('');
}

window.operateEvents = {
    'click .like': function (e, value, row, index) {
        alert('You click like action, row: ' + JSON.stringify(row));
    },
    'click .remove': function (e, value, row, index) {
        var ids = row.id;
        $(".admin-modal-del .btn-remove").attr("data-id",ids);
    }
};

function ableBoolFormatter(value){
    return  value ==true ? "able":"disabled";
}

function browserRedirect() {
    var sUserAgent = navigator.userAgent.toLowerCase();
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    var bIsMidp = sUserAgent.match(/midp/i) == "midp";
    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
    var bIsAndroid = sUserAgent.match(/android/i) == "android";
    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
    if (!(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) ){
        return true;
    }else{
        return false;
    }
}

/*
*
*
*
*       MAIN
*
*
*
* */
$(function($){
    initSwitch();
    loadTemplate();
    setMinHeight();
    pluginSettings();
});


